<template>
  <div class="exel">
       <el-breadcrumb separator="/" class="work_box">
        <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>排班管理</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="top" style="margin:15px; font-weight: bold;">
          排班明细
      </div>

      <el-button @click="importexcel" type="primary">导入</el-button>
      <el-button @click="exportexcel" type="primary">导出</el-button>
      <input ref="inputele" type="file" @change="handleChange">
      <div id="TableContainer" style="margin-top:15px"></div>
  </div>
</template>

<script setup>
import { ref } from "vue";
// 导入xlsx
// 导入file-saver
import * as XLSX from 'xlsx'
import fs from 'file-saver'
// 导入excel
var handleChange = (e)=>{
  httpRequest(e.target.files[0])
}
// 导出excel
var exportexcel =()=>{
  excelExport(document.querySelector("table"),"myexcel")
}

var httpRequest=(file)=>{
  // 获取文件，判断文件的类型
  const types = file.name.split('.')[1]
  const fileType = ['xlsx', 'xlc', 'xlm', 'xls', 'xlt'].some(
    (item) => item === types
  )
  if (!fileType) {
    ElNotification({
                title: "通知",
                message: "格式错误！请重新选择",
                type: "error",
                duration: 2000,
              });
    return
  }

  // 方式1（官网推荐、如果有报错就使用方式2）：
  // file.arrayBuffer().then(ab => {
  //   /* Parse file */
  //   const wb = XLSX.read(ab);
  //   const ws = wb.Sheets[wb.SheetNames[0]];
  //   /* Generate HTML */
  //   document.getElementById('TableContainer').innerHTML = XLSX.utils.sheet_to_html(ws)
  // });

  // 方式2：
  const reader = new FileReader()
  reader.readAsArrayBuffer(file, 'utf-8')
  reader.onloadend = function (e) {
    const file = e.target.result
    const wb = XLSX.read(file, {
      type: 'buffer'
    })

    const ws = wb.Sheets[wb.SheetNames[0]]
    /* Generate HTML */
    document.getElementById('TableContainer').innerHTML = XLSX.utils.sheet_to_html(ws)
  }
}
// 点击导入按钮，让input输入框触发点击事件
var inputele = ref()
var importexcel = ()=>{
    inputele.value.click()
}


// 自动分析dom元素导出excel
var excelExport = (table, filename) =>{
  // workbook,
  const wb = XLSX.utils.table_to_book(table)

  /* Export to file (start a download) */
  const defaultCellStyle = {
    font: { name: 'Verdana', sz: 13, color: 'FF00FF88' },
    fill: { fgColor: { rgb: 'FFFFAA00' } },
  }
  const wopts = {
    bookType: 'xlsx',
    bookSST: false,
    type: 'binary',
    cellStyle: true,
    defaultCellStyle: defaultCellStyle,
    showGridLines: false,
  }
  const wbout = XLSX.write(wb, wopts)
  const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })
  fs.saveAs(blob, filename+'.xlsx')
}

var s2ab = (s) => {
  if (typeof ArrayBuffer !== 'undefined') {
    const buf = new ArrayBuffer(s.length);
    const view = new Uint8Array(buf);
    for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
    return buf;
  } else {
    const buf = new Array(s.length);
    for (let i = 0; i !== s.length; ++i) buf[i] = s.charCodeAt(i) & 0xff;
    return buf;
  }
}
</script>

<style scoped lang='scss'>
.exel{
  input{
    display: none;
  }
  :deep(table){
    border-collapse:collapse;
    line-height: 20px;
    text-align: center;
    tr,td{
      border:1px solid #ccc;
      
    }
    tr:nth-child(even){
      background-color: lightblue;
    }
  }
} 
  

</style>